<template>
  <div class="xf-date-picker">
    <xf-input
      :valid="valid"
      :value="formatVal(value)"
      :showClearIcon="showClearIcon"
      readonly
      :showIcon="showIcon"
      :show-clear-icon="false"
      @click.native="show"
      ref="input"
      :disabled="disabled"
      :placeholder="placeholder"></xf-input>
    <mt-datetime-picker
      type="date"
      ref="picker"
      :value="initVal"
      :startDate="startDate"
      :endDate="endDate"
      @confirm="handleConfirm">
    </mt-datetime-picker>
  </div>
</template>
<script>
  import XfInput from '../xf-input/xf-input.vue'
  import {moment} from '../../common/js/util'

  const now = new Date()

  export default {
    name: 'xf-date-picker',
    props: {
      placeholder: {type: String},
      valid: {type: null},
      value: {type: null, default: ''},
      showClearIcon: {type: Boolean, default: true},
      showIcon: {type: Boolean, default: true},
      startDate: {type: null, default: () => new Date('1900/01/01')},
      endDate: {type: null, default: () => new Date(now.getTime() + 10 * 365 * 24 * 60 * 60 * 1000)},
      disabled: {type: Boolean, default: false}
    },
    components: {XfInput},
    data() {
      return {
        initVal: new Date()
      }
    },
    methods: {
      show() {
        if (this.disabled) return
        this.$refs.picker.open()
      },
      handleConfirm(val) {
        const t = moment(val).format('YYYY-MM-DD')
        this.$emit('input', t)
      },
      validValue() {
        return this.$refs.input.validValue()
      },
      formatVal(val) {
        if (val) {
          return this.$dateFormat(val).format('YYYY-MM-DD')
        } else {
          return val
        }
      }
    }
  }
</script>
<style scoped lang="scss">
  @import "../../common/style/variable";

  .xf-date-picker {
    width: 100%;
  }
</style>
